package com.risetechnology.krystalkitchen1;

import java.util.ArrayList;

import net.hockeyapp.android.CrashManager;
import net.hockeyapp.android.CrashManagerListener;
import net.hockeyapp.android.UpdateManager;
import android.app.TabActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.Toast;

import com.risetechnology.common.Background;
import com.risetechnology.common.Const;
import com.risetechnology.services.appservices.CountDownManager;

@SuppressWarnings("deprecation")
public class TabsManager extends TabActivity implements OnTabChangeListener {

	public static String APP_ID = "2c21ea01f88acc73f9057c2368a705a0";
	public static ArrayList<String> mails = new ArrayList<String>();
	public static boolean loadMailOk;
	private static TabHost tabhost;

	public static CountDownManager mCDM;
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
		
		mCDM = new CountDownManager(this);
		
		new AsyncTask<Void, Void, Void>(){
			protected void onPreExecute() {
				mails.clear();
				loadMailOk = false;
			};
			
			@Override
			protected Void doInBackground(Void... params) {
				Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null); 
				while (cursor.moveToNext()) { 
				   String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
				   

				   Cursor emails = getContentResolver().query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = " + contactId, null, null); 
				   while (emails.moveToNext()) { 
				      // This would allow you get several email addresses 
				      String emailAddress = emails.getString( 
				      emails.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA)); 
				      mails.add(emailAddress);
				   } 
				   emails.close();
				}
				cursor.close(); 
				return null;
			}
			
			protected void onPostExecute(Void result) {
				loadMailOk = true;
			};
			
		}.execute();
		
		
		// Remove title bar
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Set content for screen
		setContentView(R.layout.tabs_manager);

		// Initialize the UI
		initUI();
		
		checkForUpdates();
	}

	@Override
	protected void onResume() {
		checkForCrashes();
		super.onResume();
	}
	
	private void checkForCrashes() {
		CrashManager.register(this, APP_ID, new CrashManagerListener() {
			public void onCrashesSent() {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						Toast.makeText(TabsManager.this, "Crash data was sent. Thanks!", Toast.LENGTH_SHORT).show();
					} 
				});
			}
		});
	}

	private void checkForUpdates() {
		// Remove this for store builds!
		UpdateManager.register(this, APP_ID);
	}
	
	/**
	 * Initialize the UI for this screen
	 */
	private void initUI() {
		// Tab host
		tabhost = (TabHost) findViewById(android.R.id.tabhost);

		setupTab(Const.TAB_TIPS, R.drawable.ic_tips_tab, R.drawable.ic_tips_off,
				new Intent(this, GroupTips.class), false);
		setupTab(Const.TAB_CHEDULES, R.drawable.ic_schedules_tab, R.drawable.ic_schedules_off,
				new Intent(this, GroupCalendar.class), false);
		setupTab(Const.TAB_RECIPES, R.drawable.ic_recipes_tab, R.drawable.ic_recipes_off,
				new Intent(this, GroupRecipes.class), false);
		setupTab(Const.TAB_GLOSSARY, R.drawable.ic_shoppinglist_tab, R.drawable.ic_shoppinglist_off,
				new Intent(this, GroupShopping.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP), false);
		setupTab(Const.TAB_GLOSSARY, R.drawable.ic_glossary_tab, R.drawable.ic_glossary_off,
				new Intent(this, GroupGlossary.class), false);
		setupTab(Const.TAB_GLOSSARY, R.drawable.ic_update_tab, R.drawable.ic_update_off,
				new Intent(this, GroupUpdate.class), true);

		tabhost.setCurrentTab(0);
		tabhost.setOnTabChangedListener(this);
	}

	public TabHost getTabHost() {
		return tabhost;
	}

	private void setupTab(final String tag, int iconDrawableId, int iconSelectedDrawableId, Intent intent, boolean isLast) {

		View tabView = createTabView(tabhost.getContext(), iconDrawableId, iconSelectedDrawableId, isLast);

		TabSpec tabSpec = tabhost.newTabSpec(tag);
		tabSpec.setIndicator(tabView);
		tabSpec.setContent(intent);
		tabhost.addTab(tabSpec);
	}

	private View createTabView(final Context context, int iconDrawableId, int iconSelectedDrawableId, boolean isLast) {
		View view;
		if(isLast){
			view = LayoutInflater.from(context).inflate(R.layout.customize_tab_last, null);
		}else{
			view = LayoutInflater.from(context).inflate(R.layout.customize_tab, null);
		}

		ImageView imageViewIcon = (ImageView) view
				.findViewById(R.id.imageview_tab_icon);
		Background background = new Background(TabsManager.this, iconDrawableId, iconSelectedDrawableId);
		
		imageViewIcon.setBackgroundDrawable(background);

		return view;
	}

	public void onTabChanged(String tabId) {
		hideKeyboard();
	}

	private void hideKeyboard() {
		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		imm.hideSoftInputFromWindow(tabhost.getWindowToken(), 0);
	}
	
	@Override
	public boolean dispatchTouchEvent(final MotionEvent ev) {
	    // all touch events close the keyboard before they are processed except EditText instances.
	    // if focus is an EditText we need to check, if the touchevent was inside the focus editTexts
	    final View currentFocus = getCurrentFocus();
	    
	    if (!(currentFocus instanceof EditText) || !isTouchInsideView(ev, currentFocus)) {
	        ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
	            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	        if(currentFocus instanceof EditText){
	        	EditText edt = (EditText)currentFocus;
	        	edt.setCursorVisible(false);
	        	edt.clearFocus();
	        }
	    }
	    return super.dispatchTouchEvent(ev);
	}

	/**
	 * determine if the given motionevent is inside the given view.
	 * 
	 * @param ev
	 *            the given view
	 * @param currentFocus
	 *            the motion event.
	 * @return if the given motionevent is inside the given view
	 */
	private boolean isTouchInsideView(final MotionEvent ev, final View currentFocus) {
		if(currentFocus instanceof EditText){
        	EditText edt = (EditText)currentFocus;
        	edt.setCursorVisible(true);
        	edt.requestFocus();
        }
	    final int[] loc = new int[2];
	    currentFocus.getLocationOnScreen(loc);
	    return ev.getRawX() > loc[0] && ev.getRawY() > loc[1] && ev.getRawX() < (loc[0] + currentFocus.getWidth())
	        && ev.getRawY() < (loc[1] + currentFocus.getHeight());
	}
	
	public static void backToHome() {
		TabsManager.tabhost.setCurrentTab(0);
	}
	
	public static void goToTab(int tabId) {
		TabsManager.tabhost.setCurrentTab(tabId);
	}
	
}
